import { Toast } from "antd-mobile";
import axios from "axios"

let baseUrl = "";
let $pre = "";
// 环境判断
if(process.env.NODE_ENV === "development"){
    baseUrl = "/api"
    $pre = "http://localhost:1000"
}
export {$pre}

// 请求拦截
axios.interceptors.request.use(config =>{
    config.url = baseUrl + config.url

    if(config.url != baseUrl + "/api/login" && config.url != baseUrl + "/api/register"){
        config.headers.authorization = JSON.parse(sessionStorage.getItem("isLogin")).token
    }
    return config
})
// 响应拦截
axios.interceptors.response.use(res=>{
    console.group("发起请求的地址"+res.config.url)
    console.log(res);
    console.groupEnd()

    if(res.data.code !== 200){
        Toast.show({
            content:res.data.msg
        })
    }

    if(res.data.msg === "登录已过期或访问权限受限"){
        sessionStorage.removeItem("isLogin")
        window.open("/","_self")
    }
    return res
})

// 请求方法封装
export const get = (url,params={})=>{
    return axios({
        url,
        method:"get",
        params
    })
}

export const post = (url,params,haveFile=false)=>{
    let d = null;
    if(haveFile){
        d = new FormData()
        for(let key in params){
            d.append(key,params[key])
        }
    }else{
        d = params
    }

    return axios({
        url,
        method:"post",
        data:d,
    })
}